import { isHasToken } from '@/utils/storage'
import React from 'react'
import { Route, Redirect, useLocation } from 'react-router-dom'

/* export default function PrivateRoute(props) {
  return <Route {...props} />
} */
// 把 props 对象里面的 component 单独解构出来
// 剩下的所有参数都放到 rest 对象里面了
/* export default function PrivateRoute({ component, ...rest }) {
  return (
    <Route
      {...rest}
      render={() => {
        if (isHasToken()) {
          return component
        } else {
          return <Redirect to='/login' />
        }
      }}
    />
  )
} */

// 支持两种写法
{
  /* <PrivateRoute path='/home' component={Layout} /> */
}
{
  /* <PrivateRoute path='/home'>
  <Layout />
</PrivateRoute> */
}
export default function PrivateRoute({
  component: Component,
  children,
  ...rest
}) {
  const location = useLocation()
  return (
    <Route
      {...rest}
      render={() => {
        if (isHasToken()) {
          return children ? children : <Component />
        } else {
          // return <Redirect to='/login' />
          // Redirect 默认是 replace，而不是 push 的操作
          return (
            <Redirect
              to={{
                pathname: '/login',
                // state 是固定的
                state: {
                  // from 代表需要传递参数，传递是当前的路由地址
                  from: location.pathname,
                },
              }}
            />
          )
        }
      }}
    />
  )
}
